package com.sincon.system.service.impl;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.sincon.common.constant.Constants;
import com.sincon.system.domain.QRCodeResponse;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class BilibiliService {
    
    private static final String QR_CODE_URL = "https://passport.bilibili.com/x/passport-login/web/qrcode/generate";
    private static final String QR_CODE_CHECK_URL = "https://passport.bilibili.com/x/passport-login/web/qrcode/poll";
    
    private final CloseableHttpClient httpClient;
    private final RequestConfig requestConfig;

    @Autowired
    private TokenBilibiliService tokenService;


    
    public BilibiliService() {
        this.requestConfig = RequestConfig.custom()
            .setConnectTimeout(5000)
            .setSocketTimeout(5000)
            .build();
            
        this.httpClient = HttpClients.custom()
            .setDefaultRequestConfig(requestConfig)
            .build();
    }
    
    public QRCodeResponse getLoginQRCode() {
        try {
            HttpGet httpGet = new HttpGet(QR_CODE_URL);
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            
            HttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            
            JSONObject jsonObject = JSON.parseObject(responseBody);
            
            if (jsonObject.getInteger("code") == 0) {
                JSONObject data = jsonObject.getJSONObject("data");
                QRCodeResponse qrCodeResponse = new QRCodeResponse();
                qrCodeResponse.setQrcode_key(data.getString("qrcode_key"));
                qrCodeResponse.setQrcode_base64(generateQRCode(data.getString("url")));
                return qrCodeResponse;
            }
            
            throw new RuntimeException("获取二维码失败：" + responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取二维码失败", e);
        }
    }
    
    public JSONObject checkLoginStatus(String qrcodeKey) {
        try {
            String url = QR_CODE_CHECK_URL + "?qrcode_key=" + URLEncoder.encode(qrcodeKey, StandardCharsets.UTF_8.name());
            HttpGet httpGet = new HttpGet(url);
            
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept", "application/json, text/plain, */*");
            httpGet.setHeader("Origin", "https://www.bilibili.com");
            httpGet.setHeader("Referer", "https://www.bilibili.com/");
            
            HttpResponse response = httpClient.execute(httpGet);
            
            List<String> cookies = new ArrayList<>();
            Header[] headers = response.getHeaders("Set-Cookie");
            if (headers != null && headers.length > 0) {
                for (Header header : headers) {
                    cookies.add(header.getValue());
                }
            }
            
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);

            JSONObject jsonObject = JSON.parseObject(responseBody);
            
            if (!cookies.isEmpty()) {
                //登陆成功之后才会有COOKIES
                jsonObject.put("cookies", cookies);
                //根据COOKIES去生成TOKEN
                StringBuffer cookie = new StringBuffer();
                for (String cookieCut : cookies) {
                    cookie = cookie.append(cookieCut+"; ");
                }
                JSONObject userInfo = getUserInfo(cookie.toString());
                jsonObject.put(Constants.TOKEN,tokenService.createBilibiliTokenAuth(userInfo));


            }
            
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("检查登录状态失败", e);
        }
    }
    
    private String generateQRCode(String content) {
        try {
            QrConfig config = new QrConfig(300, 300);
            config.setMargin(1);
            return QrCodeUtil.generateAsBase64(content, config, "png");
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("生成二维码失败", e);
        }
    }
    
    public JSONObject getUserInfo(String cookie) {
        try {
            HttpGet httpGet = new HttpGet("https://api.bilibili.com/x/space/myinfo");
            
            // 设置请求头
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            httpGet.setHeader("Cookie", cookie);
            
            HttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            
            return JSON.parseObject(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("获取用户信息失败", e);
        }
    }
    
    public JSONObject getLikedVideos(String cookie, int pageNum, int pageSize) {
        try {
            // 需要添加用户mid参数
            String mid = extractMidFromCookie(cookie);
            // 修改为正确的点赞视频API
            String url = String.format("https://api.bilibili.com/x/space/like/video?vmid=%s&pn=%d&ps=%d", mid, pageNum, pageSize);
            HttpGet httpGet = new HttpGet(url);
            
            // 设置请求头
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            httpGet.setHeader("Cookie", cookie);
            httpGet.setHeader("Referer", "https://space.bilibili.com");
            
            HttpResponse response = httpClient.execute(httpGet);
            String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
            
            // 打印响应内容用于调试
            System.out.println("API Response: " + responseBody);
            
            // 检查响应状态码
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                throw new RuntimeException("API request failed with status code: " + statusCode);
            }
            
            // 检查响应内容是否为空
            if (responseBody == null || responseBody.trim().isEmpty()) {
                throw new RuntimeException("Empty response from API");
            }
            
            return JSON.parseObject(responseBody);
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject errorResponse = new JSONObject();
            errorResponse.put("code", -1);
            errorResponse.put("message", "获取点赞视频失败: " + e.getMessage());
            return errorResponse;
        }
    }
    
    private String extractMidFromCookie(String cookie) {
        try {
            String[] cookies = cookie.split(";");
            for (String c : cookies) {
                if (c.trim().startsWith("DedeUserID=")) {
                    return c.trim().substring("DedeUserID=".length());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new RuntimeException("无法从Cookie中获取用户ID");
    }
} 